<template>
  <el-dialog
    v-model="visible"
    title="批量异常识别分析"
    width="1400px"
    @close="handleClose"
  >
    <div class="space-y-6">
      <!-- 车辆选择 -->
      <div class="bg-gray-50 p-4 rounded-lg">
        <div class="flex items-center justify-between mb-3">
          <h3 class="text-sm font-medium text-gray-900">选择分析车辆（最多10辆）</h3>
          <div class="flex space-x-2">
            <el-button size="small" @click="selectHighRiskVehicles">选择高风险车辆</el-button>
            <el-button size="small" @click="clearSelection">清空选择</el-button>
          </div>
        </div>
        <div class="grid grid-cols-2 md:grid-cols-5 gap-2">
          <div 
            v-for="vehicle in availableVehicles" 
            :key="vehicle.id"
            class="flex items-center"
          >
            <el-checkbox 
              v-model="selectedVehicleIds"
              :label="vehicle.id"
              :disabled="!canSelectMore && !selectedVehicleIds.includes(vehicle.id)"
            >
              <span class="text-sm" :class="getRiskColor(vehicle.riskLevel)">
                {{ vehicle.id }}
              </span>
            </el-checkbox>
          </div>
        </div>
      </div>

      <!-- 批量分析结果 -->
      <div v-if="selectedVehicles.length > 0" class="space-y-6">
        <!-- 三维空间可视化 -->
        <div class="bg-white border rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">三维热工况空间分析</h3>
          <div class="h-96">
            <v-chart :option="threeDSpaceOption" class="w-full h-full" />
          </div>
          <div class="mt-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
            <div class="text-sm font-medium text-yellow-800 mb-2">异常空间识别结果</div>
            <div class="text-sm text-yellow-700">
              {{ anomalyResults.join('、') }}已落入异常空间，需要启动异常处理路径
            </div>
          </div>
        </div>

        <!-- CTI 排序表 -->
        <div class="bg-white border rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">CTI 批量计算与排序</h3>
          <el-table 
            :data="ctiSortedData" 
            style="width: 100%"
            @row-click="highlightVehicle"
            highlight-current-row
          >
            <el-table-column prop="rank" label="排名" width="80" />
            <el-table-column prop="vehicleId" label="车辆ID"  />
            <el-table-column prop="model" label="车型" width="120" />
            <el-table-column prop="cti" label="CTI 值" width="100">
              <template #default="{ row }">
                <span :class="getCtiColor(row.cti)">{{ row.cti }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)" size="small">
                  {{ row.statusText }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="thmVector" label="热工况向量" width="180">
              <template #default="{ row }">
                <span class="font-mono text-sm">
                  [{{ row.thmVector.map((v: number) => v.toFixed(2)).join(',') }}]
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="riskLevel" label="风险等级" width="100">
              <template #default="{ row }">
                <el-tag :type="getRiskTagType(row.riskLevel)" size="small">
                  {{ getRiskText(row.riskLevel) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="viewDetails(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 批量处理操作 -->
        <div class="bg-white border rounded-lg p-4">
          <h3 class="text-lg font-semibold text-gray-900 mb-4">批量处理操作</h3>
          <div class="flex space-x-4">
            <el-button 
              type="danger" 
              :disabled="anomalyVehicles.length === 0"
              @click="batchProcessAnomalies"
            >
              批量处理异常车辆 ({{ anomalyVehicles.length }}辆)
            </el-button>
            <el-button 
              type="warning"
              :disabled="warningVehicles.length === 0"
              @click="batchMonitorWarnings"
            >
              批量加入重点监控 ({{ warningVehicles.length }}辆)
            </el-button>
            <el-button type="primary" @click="exportBatchReport">
              导出批量分析报告
            </el-button>
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div class="bg-red-50 border border-red-200 rounded-lg p-4">
            <div class="text-sm text-red-600 mb-1">异常车辆</div>
            <div class="text-2xl font-bold text-red-800">{{ anomalyVehicles.length }}</div>
            <div class="text-xs text-red-500">CTI ≤ 0.01</div>
          </div>
          <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div class="text-sm text-yellow-600 mb-1">预警车辆</div>
            <div class="text-2xl font-bold text-yellow-800">{{ warningVehicles.length }}</div>
            <div class="text-xs text-yellow-500">0.01 < CTI ≤ 0.05</div>
          </div>
          <div class="bg-green-50 border border-green-200 rounded-lg p-4">
            <div class="text-sm text-green-600 mb-1">正常车辆</div>
            <div class="text-2xl font-bold text-green-800">{{ normalVehicles.length }}</div>
            <div class="text-xs text-green-500">CTI > 0.05</div>
          </div>
          <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div class="text-sm text-blue-600 mb-1">平均CTI</div>
            <div class="text-2xl font-bold text-blue-800">{{ averageCTI }}</div>
            <div class="text-xs text-blue-500">所有选中车辆</div>
          </div>
        </div>
      </div>

      <div v-else class="text-center text-gray-500 py-8">
        请选择车辆进行批量异常识别分析
      </div>
    </div>
    
    <template #footer>
      <div class="flex justify-end space-x-2">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="goToChargingPriority">前往调度优先级</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { ScatterChart } from 'echarts/charts'
import { 
  GridComponent, 
  TooltipComponent, 
  LegendComponent,
  VisualMapComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { ElMessage } from 'element-plus'
import { Scatter3DChart } from 'echarts-gl/charts'
import { Grid3DComponent } from 'echarts-gl/components'

use([
  CanvasRenderer,
  ScatterChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  VisualMapComponent,
  Scatter3DChart,
  Grid3DComponent
])

const props = defineProps<{
  modelValue: boolean
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

const router = useRouter()
const store = useAppStore()

const visible = ref(false)
const selectedVehicleIds = ref<string[]>([])
const highlightedVehicle = ref<string>('')

const availableVehicles = computed(() => store.vehicles)
const selectedVehicles = computed(() => 
  store.vehicles.filter(v => selectedVehicleIds.value.includes(v.id))
)
const canSelectMore = computed(() => selectedVehicleIds.value.length < 10)

watch(() => props.modelValue, (val) => {
  visible.value = val
})

const ctiSortedData = computed(() => {
  return selectedVehicles.value
    .map(vehicle => ({
      vehicleId: vehicle.id,
      model: vehicle.model,
      cti: store.calculateCTI(vehicle.thmVector).toFixed(3),
      ctiValue: store.calculateCTI(vehicle.thmVector),
      thmVector: vehicle.thmVector,
      riskLevel: vehicle.riskLevel,
      status: store.calculateCTI(vehicle.thmVector) <= 0.01 ? 'anomaly' : 
               store.calculateCTI(vehicle.thmVector) <= 0.05 ? 'warning' : 'normal',
      statusText: store.calculateCTI(vehicle.thmVector) <= 0.01 ? '异常' : 
                  store.calculateCTI(vehicle.thmVector) <= 0.05 ? '预警' : '正常'
    }))
    .sort((a, b) => a.ctiValue - b.ctiValue)
    .map((item, index) => ({ ...item, rank: index + 1 }))
})

const anomalyVehicles = computed(() => 
  ctiSortedData.value.filter(v => v.status === 'anomaly')
)

const warningVehicles = computed(() => 
  ctiSortedData.value.filter(v => v.status === 'warning')
)

const normalVehicles = computed(() => 
  ctiSortedData.value.filter(v => v.status === 'normal')
)

const averageCTI = computed(() => {
  if (selectedVehicles.value.length === 0) return '0.000'
  const sum = selectedVehicles.value.reduce((acc, v) => acc + store.calculateCTI(v.thmVector), 0)
  return (sum / selectedVehicles.value.length).toFixed(3)
})

const anomalyResults = computed(() => 
  anomalyVehicles.value.map(v => v.vehicleId)
)

const threeDSpaceOption = computed(() => {
  const colors = ['#ef4444', '#f59e0b', '#22c55e', '#3b82f6', '#8b5cf6']
  
  return {
    tooltip: {
      formatter: (params: any) => {
        const data = params.data
        return `车辆: ${data[3]}<br/>
                温度: ${data[0].toFixed(2)}<br/>
                放电时长: ${data[1].toFixed(2)}<br/>
                功率: ${data[2].toFixed(2)}<br/>
                CTI: ${store.calculateCTI([data[0], data[1], data[2]]).toFixed(3)}`
      }
    },
    grid3D: {
      viewControl: {
        autoRotate: true,
        autoRotateSpeed: 5
      }
    },
    xAxis3D: {
      type: 'value',
      name: '温度归一化',
      min: 0,
      max: 1
    },
    yAxis3D: {
      type: 'value',
      name: '放电时长归一化',
      min: 0,
      max: 1
    },
    zAxis3D: {
      type: 'value',
      name: '功率归一化',
      min: 0,
      max: 1
    },
    series: [{
      type: 'scatter3D',
      data: selectedVehicles.value.map((vehicle, index) => [
        vehicle.thmVector[0],
        vehicle.thmVector[1],
        vehicle.thmVector[2],
        vehicle.id
      ]),
      symbolSize: (data: any) => {
        const cti = store.calculateCTI([data[0], data[1], data[2]])
        return cti <= 0.01 ? 20 : cti <= 0.05 ? 15 : 10
      },
      itemStyle: {
        color: (params: any) => {
          const cti = store.calculateCTI([params.data[0], params.data[1], params.data[2]])
          return cti <= 0.01 ? '#ef4444' : cti <= 0.05 ? '#f59e0b' : '#22c55e'
        }
      }
    }]
  }
})

const getRiskColor = (riskLevel: string) => {
  switch (riskLevel) {
    case 'high': return 'text-red-600'
    case 'warning': return 'text-yellow-600'
    case 'low': return 'text-green-600'
    default: return 'text-gray-600'
  }
}

const getCtiColor = (cti: string) => {
  const value = parseFloat(cti)
  if (value <= 0.01) return 'text-red-600 font-bold'
  if (value <= 0.05) return 'text-yellow-600 font-bold'
  return 'text-green-600'
}

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'anomaly': return 'danger'
    case 'warning': return 'warning'
    case 'normal': return 'success'
    default: return 'info'
  }
}

const getRiskTagType = (riskLevel: string) => {
  switch (riskLevel) {
    case 'high': return 'danger'
    case 'warning': return 'warning'
    case 'low': return 'success'
    default: return 'info'
  }
}

const getRiskText = (riskLevel: string) => {
  switch (riskLevel) {
    case 'high': return '高风险'
    case 'warning': return '风险预警'
    case 'low': return '低风险'
    default: return '未知'
  }
}

const selectHighRiskVehicles = () => {
  selectedVehicleIds.value = store.vehicles
    .filter(v => v.riskLevel === 'high')
    .slice(0, 10)
    .map(v => v.id)
}

const clearSelection = () => {
  selectedVehicleIds.value = []
}

const highlightVehicle = (row: any) => {
  highlightedVehicle.value = row.vehicleId
}

const viewDetails = (row: any) => {
  const vehicle = store.vehicles.find(v => v.id === row.vehicleId)
  if (vehicle) {
    store.setCurrentVehicle(vehicle)
    ElMessage.success(`已选择车辆 ${vehicle.id}`)
  }
}

const batchProcessAnomalies = () => {
  ElMessage.success(`已将 ${anomalyVehicles.value.length} 辆异常车辆加入紧急处理队列`)
}

const batchMonitorWarnings = () => {
  ElMessage.success(`已将 ${warningVehicles.value.length} 辆预警车辆加入重点监控`)
}

const exportBatchReport = () => {
  const data = {
    analysisTime: new Date().toISOString(),
    totalVehicles: selectedVehicles.value.length,
    anomalyCount: anomalyVehicles.value.length,
    warningCount: warningVehicles.value.length,
    normalCount: normalVehicles.value.length,
    averageCTI: parseFloat(averageCTI.value),
    vehicles: ctiSortedData.value
  }
  
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `batch_analysis_report_${new Date().toISOString().slice(0, 10)}.json`
  a.click()
  URL.revokeObjectURL(url)
  
  ElMessage.success('批量分析报告已导出')
}

const goToChargingPriority = () => {
  if (anomalyVehicles.value.length > 0) {
    store.setCurrentVehicle(store.vehicles.find(v => v.id === anomalyVehicles.value[0].vehicleId)!)
  }
  handleClose()
  router.push('/priority')
}

const handleClose = () => {
  visible.value = false
  emit('update:modelValue', false)
}
</script>